<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use fast\Random;

/**
 * 员工管理员管理
 *
 * @icon fa fa-circle-o
 */
class Staff extends Backend
{
    
    /**
     * Staff模型对象
     * @var \app\admin\model\Staff
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Staff;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                $region_address = db('area')->where(['id'=>$v->area_one_id])->value('name');
                $city = db('area')->where(['id'=>$v->area_tow_id])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                }
                $v->region_address = $region_address?$region_address:'';

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig("updatecs", $this->auth->check("staff/updatecs"));
        $this->assignconfig("staff_users", $this->auth->check("user/user/staff_users"));
        $this->assignconfig("staff_volunteers", $this->auth->check("volunteer/staff_volunteers"));
        $this->assignconfig("indexss", $this->auth->check("volunteer/indexss"));
        return $this->view->fetch();
    }

    /**
     * 區域員工
     */
    public function area_staff($ids)
    {
        $this->assignconfig("ids", $ids);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($where)
                    ->where(['area_tow_id'=>$ids])
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);

                $region_address = db('area')->where(['id'=>$v->area_one_id])->value('name');
                $city = db('area')->where(['id'=>$v->area_tow_id])->value('name');
                if ( $city ) {
                    $region_address = $region_address.$city;
                }
                $v->region_address = $region_address?$region_address:'';
                $area = db('area')->where(['id'=>$v->area_one_id])->value('name');
                $two_area = db('area')->where(['id'=>$v->area_tow_id])->value('name');
                $v->area = $area.$two_area;

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }
    

    /**
     * 启用合作
     */
    public function updatecs($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $title = '';
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['status'] == 'hidden') {
                        $where = ['status'=>'normal'];
                    }else{
                        $where = ['status'=>'hidden'];;
                    }
                    $count += $v->save($where);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('操作失败'));
            }
        }
        $this->error(__('操作失败', 'ids'));
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $labels = $this->request->post("labels/a");
                $labelss = $this->request->post("labelss/a");
                $params = $this->preExcludeFields($params);
                $count = db('admin')->where(['username'=>$params['username']])->count();
                if ( $count ) {
                    $this->error('賬號重復，請更換賬號');
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['bright_password']) . $params['salt']);
                $params['area_one_id'] = input('province',0);
                $params['area_tow_id'] = input('city',0);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $id = $this->model->id;
                    if ( $labels ) {
                        db('user')->where(['id'=>['in',$labels]])->update(['staff_id'=>$id]);
                    }
                    if ( $labelss ) {
                        db('volunteer')->where(['id'=>['in',$labelss]])->update(['staff_id'=>$id]);
                    }
                    // db('staff_auth_group_access')->insert(['uid' => $this->model->id, 'group_id' => 1]);
                    $this->addAdmin($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function addAdmin($params)
    {
        $data = [
            'username'=>$params['username'],
            'nickname'=>$params['nickname'],
            'password'=>$params['bright_password'],
            'salt'=>$params['salt'],
        ];
        $data['password'] = md5(md5($data['password']) . $data['salt']);
        $data['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
        $model =  model('Admin');
        var_dump($data);
        $result = $model->validate('Admin.add')->save($data);
        if ($result === false) {
            exception($this->model->getError());
        }
        $group = [8];
        $dataset = [];
        foreach ($group as $value) {
            $dataset[] = ['uid' => $model->id, 'group_id' => $value];
        }
        model('AuthGroupAccess')->saveAll($dataset);

    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row['labels'] = db('user')->field('*,nickname as name')->where(['staff_id'=>$row['id']])->select();
        $row['labelss'] = db('volunteer')->where(['staff_id'=>$row['id'],'deletetime'=>null])->select();
        $province = db('region')->field('id as value, name')->where(['id'=>$row['area_one_id']])->find();
        $city = db('region')->field('id as value, name')->where(['id'=>$row['area_tow_id']])->find();
        $this->view->assign("province", $province);
        $this->view->assign("city", $city);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $labels = $this->request->post("labels/a");
                $labelss = $this->request->post("labelss/a");
                $params = $this->preExcludeFields($params);
                $result = false;
                $count = db('staff')->where(['id'=>['neq',$row['id']],'username'=>$params['username']])->count();
                if ( $count ) {
                    $this->error('賬號重復，請更換賬號');
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['bright_password']) . $params['salt']);
                $params['area_one_id'] = input('province',0);
                $params['area_tow_id'] = input('city',0);
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                        db('user')->where(['staff_id'=>$row['id']])->update(['staff_id'=>0]);
                    if ( $labels ) {
                        db('user')->where(['id'=>['in',$labels]])->update(['staff_id'=>$row['id']]);
                    }
                        db('volunteer')->where(['staff_id'=>$row['id']])->update(['staff_id'=>0]);
                    if ( $labelss ) {
                        db('volunteer')->where(['id'=>['in',$labelss]])->update(['staff_id'=>$row['id']]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    
                    db('user')->where(['staff_id'=>$v['id']])->update(['staff_id'=>0]);
                    db('volunteer')->where(['staff_id'=>$v['id']])->update(['staff_id'=>0]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    

}
